package com.tomowork.controller;

import com.tomowork.commons.ServerResponse;
import com.tomowork.entity.Dept;
import com.tomowork.entity.Emp;
import com.tomowork.exception.ParamException;
import com.tomowork.service.IEmpService;
import com.tomowork.utils.PageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/emp/")
public class EmpController {
    @Autowired
    private IEmpService empService ;

    private static Logger logger = LoggerFactory.getLogger(EmpController.class) ;



    //进行分页查询
    @RequestMapping(value = "select/all")
    public  ServerResponse<PageUtil> findAll(@RequestParam(name = "pageNum",defaultValue = "1") int pageNum,
                              @RequestParam(name = "pageSize",defaultValue = "6") int pageSize){
        PageUtil<Emp> page = new PageUtil<>(5) ;
        page.setPageNum(pageNum);
        page.setPageSize(pageSize);
        page.setAllRow(empService.getAllCount());
        if(pageNum>page.getAllPageNum()){
            pageNum = page.getAllPageNum() ;
            page.setPageNum(pageNum);
        }
        page.setList(empService.selectAll((pageNum-1)*pageSize,pageSize)); //因为hibernate是从0开始
        return ServerResponse.success("请求成功",page) ;
    }
    //进行部门的删除操作
    @RequestMapping("delete/{empno}")
    public ServerResponse deleteEmp(@PathVariable("empno") Integer empno){
        if(empService.delete(empno)){
            return ServerResponse.success("数据删除成功") ;
        }
        return ServerResponse.fail("数据删除失败") ;
    }
    //进行数据的编辑操作
    @RequestMapping("update")
    public ServerResponse update(Emp emp){
        boolean result = empService.update(emp);
        if(result){
            return ServerResponse.success("更新成功") ;
        }else{
            return ServerResponse.fail("更新失败") ;
        }
    }


    //进行雇员的保存
    @RequestMapping("/save")
    public ServerResponse save(@Valid Emp emp,Errors errors,Integer deptno){
        empService.insert(emp,deptno);
        return ServerResponse.success("雇员保存成功") ;

    }
    //进行数据的查找
    @RequestMapping(value = "/emp/select/{empno}",method = RequestMethod.GET)
    public ServerResponse select(@PathVariable("empno") Integer empno){
        Emp emp = empService.selectByEmpno(empno) ;
        if(emp!=null){
            return ServerResponse.success("操作成功",emp) ;
        }
        return ServerResponse.fail("您查找的数据不存在") ;
    }
}
